<template>
  <div class="orderDish">
    <el-row :gutter="24">
      <el-col :span="16" class="el-col-left">
        <el-row :gutter="24">
          <el-col :span="6">
            <el-input v-model="value" type="text" maxlength="2" size="small"
                      oninput="value=value.replace(/[^\d.]/g,'')" placeholder="请输入桌台号">
            </el-input>
          </el-col>
          <el-col :span="2">
            <el-button type="primary" size="small" plain @click="lockTable">锁定</el-button>
          </el-col>
          <el-col :span="8">
            <template>
              <el-tabs v-model="activeName" @tab-click="handleClick" :stretch="true">
                <el-tab-pane label="外卖" name="1"></el-tab-pane>
                <el-tab-pane label="自助点餐" name="2"></el-tab-pane>
                <el-tab-pane label="预定" name="3"></el-tab-pane>
              </el-tabs>
            </template>
          </el-col>
          <el-col :span="6">
            <el-input v-model="dishName" type="text" size="small" placeholder="请输入菜名搜索" suffix-icon="el-icon-search"
                      @keyup.enter.native="searchDish('dishName')">
            </el-input>
          </el-col>
          <el-col :span="2">
            <el-button type="primary" size="small" plain @click="searchDish">搜索</el-button>
          </el-col>
        </el-row>
        <Dish></Dish>
      </el-col>
      <el-col :span="8" align="center" class="el-col-right">
        <el-card class="box-card">
          <div>
            <div class="right-top-table">
              <template>
                <el-table :data="cartData" border style="width: 100%"
                          :header-cell-style="{background:'#d2d0d0',color:'#4b4949',textAlign: 'center'}"
                          :cell-style="{textAlign:'center'}">
                  <el-table-column prop="dishName" label="菜品名称" min-width="40%"></el-table-column>
                  <el-table-column prop="dishPrice" label="单价" min-width="30%"></el-table-column>
                  <el-table-column label="数量" min-width="30%">
                    <template slot-scope="scope">
                      <el-input-number v-model="scope.row.dishNum" @change="handleChange(scope.row)" :min="1" :max="10"
                                       size="mini"></el-input-number>
                    </template>
                  </el-table-column>
                </el-table>
              </template>
            </div>
            <div class="right-bottom-order">
              <div class="bottom-order-top">
                <span>金额： ￥</span> <b style="font-size: 30px">{{ totalPrice(1) }}</b>
                <span style="margin-left: 100px" @click="clearAll">清 空</span>
              </div>
              <div class="bottom-order-bootom">
                <el-button type="primary" @click="submitOrder">下单</el-button>
              </div>
            </div>
          </div>
        </el-card>


      </el-col>
    </el-row>

  </div>
</template>
<script>
import Dish from "@/components/Dish";
import BaseUrl from "@/http/BaseUrl";
import TokenAxios from "@/http/TokenAxios";

export default {
  components: {
    Dish
  },
  data() {
    return {
      cartData: [],
      dishesIdList: [],
      value: localStorage.getItem('tableId'),
      activeName: '2',
      dishName:''
    }
  },
  computed: {
    totalPrice() {
      return function (index) {
        let totalPrice = 0;
        this.cartData.forEach(element => {
          totalPrice += (element.dishPrice * element.dishNum)
        });
        totalPrice += 0;
        return totalPrice.toFixed(2)
      }
    },
  },
  methods: {
    clearAll() {//清空购物车
      this.$confirm('您确定清空购物车?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let dishId = 10000;
        let url = BaseUrl.FRONT_CART + '/carts/delete/' + dishId;
        console.log('url:' + url)

        TokenAxios.get(url).then((response) => {
          let jsonResult = response.data;
          if (jsonResult.state == 20000) {
            this.$message({
              type: 'success',
              duration: 1200,
              message: '已清空购物车！'
            });
            this.loadCartList();
          } else {
            this.$message.error(jsonResult.message);
          }
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          duration: 1200,
          message: '已取消操作！'
        });
      });
    },
    handleClick(tab) {//点击菜系导航栏
      console.log(tab.name)
      this.categoryIndex = tab.name;
    },
    lockTable() {//点击锁定按钮
      if (this.table !== null) {

      }
    },
    searchDish(){
      if (this.dishName != null && this.dishName.trim() !== ''){
        console.log(this.dishName);
        localStorage.setItem('dishName',this.dishName);
        location.reload();
      }
    },
    handleChange(value) {//点击购物车数量加减
      console.log(value)
      let url = BaseUrl.FRONT_CART + '/carts/update/' + value.dishId + '/' + value.dishNum;
      console.log('url:' + url)

      TokenAxios.post(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.cartData = jsonResult.data;
          this.loadCartList();
        } else {
          this.$message.error(jsonResult.message);
        }
      });
    },
    loadCartList() {//加载购物车列表
      let url = BaseUrl.FRONT_CART + '/carts';
      console.log('url:' + url)

      TokenAxios.get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.cartData = jsonResult.data;
        } else {
          this.$message.error(jsonResult.message);
        }
      });
    },
    submitOrder() {//点击提交订单按钮
      this.dishesIdList =[];
      this.cartData.forEach(it => {
        this.dishesIdList.push(it.dishId);
      })
      console.log("slka"+this.dishesIdList)
      if (this.value !== null){
        this.createOrder();
        this.loadCartList();
      }
      if (this.value == null) {
        this.$prompt('未选择桌台，请输入桌台号', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /^(?:[0-9]|[0-9][0-9])$/,
          inputErrorMessage: '格式不正确，请输入两位及以内数字'
        }).then(({value}) => {
          this.$message({
            type: 'success',
            duration:1000,
            message: '你锁定的桌台是: ' + value
          });
          this.value = value;
          this.createOrder();
          this.loadCartList();
        }).catch(() => {
          this.$message({
            type: 'info',
            duration:1000,
            message: '取消输入'
          });
        });
      }
    },
    createOrder() {//新建订单
      let url = BaseUrl.FRONT_ORDER + '/orders/create';
      console.log('url:' + url)

      let order = {
        tableId: this.value,
        orderMethod: this.activeName,
        dishesIdList: this.dishesIdList
      }
      console.log(order)
      TokenAxios.post(url, order).then((response) => {
        console.log(order);
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.$message({
            type: 'success',
            duration: 1000,
            message: '下单成功！'
          });
          this.loadCartList();
        } else {
          this.$message.error(jsonResult.message);
        }
      });
    },
  },
  mounted() {
    this.loadCartList();
  }
}
</script>
<style scoped lang="less">
/*
 页面右边部分
 */
.el-col-right {

  .right-bottom-order {
    text-align: left;
    height: 100px;
    margin-left: 100px;

    .bottom-order-top {
      margin: 70px 0 25px 0
    }

    button {
      width: 320px;
      border-radius: 10px;
    }
  }

}

.el-col-right .el-input-number {
  width: 99px;
}
</style>